#include<iostream>
#include<cstdio>
#include<unistd.h>
#include<cstdlib>
#include<string>
#include<cstring>
#include<sys/wait.h>
#include<sys/types.h>

#define N 2
#define NUM 1024

using namespace std;

// child
void Writer(int wfd)
{
    string mes = "Hello? I' m a child";
    pid_t self = getpid();
    int number = 0;
    char buffer[NUM] = {0};
    while(true)
    {
        sleep(1);
        buffer[0] = {0}; // 字符串清空，把数组当作字符串
        snprintf(buffer, sizeof(buffer), "%s-%d-%d", mes.c_str(), self, number++);
        cout<<buffer<<endl;
        write(wfd, buffer, strlen(buffer));

        if(number == 5) break;
    }
}

//father
void Reader(int rfd)
{
    char buffer[NUM];

    while(true)
    {
        buffer[0] = 0;
        ssize_t n = read(rfd, buffer, sizeof(buffer));
        if(n > 0)
        {
            buffer[n] = 0;
            cout<<"father got a message["<<getpid()<<"]# "<<buffer<<endl;
        }
        else if(n == 0)
        {
            cout<<"father read file done!"<<endl;
            break;
        }
        else break;
    }
}

int main()
{
    int pipefd[N] = {0};
    int n = pipe(pipefd);
    if(n < 0) return 1;

    // cout<<"pipefd[0]: "<<pipefd[0]<<", pipefd[1]: "<<pipefd[1]<<endl;
    // child -> w, father -> r
    pid_t id = fork();
    if(id < 0) return 2;
    if(id == 0) // child
    {
        close(pipefd[0]);

        // IPC code
        Writer(pipefd[1]);

        close(pipefd[1]);
    }
    // father
    close(pipefd[1]);

    // IPC code
    Reader(pipefd[0]);

    pid_t rid = waitpid(id, nullptr, 0);
    if(rid < 0) return 3;

    close(pipefd[0]);
    sleep(5);

    return 0;
}
